﻿using ciji.Application.Dto;
using ciji.Core;
using Furion.DatabaseAccessor;
using Microsoft.AspNetCore.Components.Forms;
using SqlSugar.Extensions;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ciji.Application.Data
{
    /// <summary>
    /// 工作台
    /// </summary>
    [ApiDescriptionSettings("工作台", Order = 800, Description = "工作台")]
    public class WorkService: IDynamicApiController
    {
        private SqlSugarRepository<cts_Word> _wordRep;
        private SqlSugarRepository<cts_ProjectReport> _reportRep;
        private SqlSugarRepository<cts_Opinion> _optionRep;
        private SqlSugarRepository<cts_CheckOnWorkRule> _checkOnWorkRuleRep;
        private SqlSugarRepository<cts_CheckOnWork> _checkOnWorkRep;
        private SqlSugarRepository<cts_PhotoGroup> _photoGroupRep;

        private SqlSugarRepository<cts_Photo> _photoRep;
        public WorkService(SqlSugarRepository<cts_Word> wordRep
            , SqlSugarRepository<cts_ProjectReport> reportRep
            , SqlSugarRepository<cts_Opinion> optionRep
            , SqlSugarRepository<cts_CheckOnWorkRule> checkOnWorkRuleRep
            , SqlSugarRepository<cts_CheckOnWork> checkOnWorkRep
            , SqlSugarRepository<cts_PhotoGroup> photoGroupRep
            , SqlSugarRepository<cts_Photo> photoRep) {
            _wordRep = wordRep;
            _reportRep = reportRep;
            _optionRep = optionRep;
            _checkOnWorkRuleRep = checkOnWorkRuleRep;
            _checkOnWorkRep = checkOnWorkRep;
            _photoGroupRep = photoGroupRep;
            _photoRep = photoRep;


        }
        /// <summary>
        /// 查询知识库
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public SqlSugarPagedXList<cts_Word> SearchWord(SearchWordInput input)
        {

          return  _wordRep.AsQueryable().WhereIF(input.wordsource > -1, m => m.WordSource == input.wordsource)
                .WhereIF(input.wordtype > -1, m => m.WordType == input.wordtype)
                .WhereIF(!string.IsNullOrEmpty(input.str), m => m.Name.Contains(input.str) || m.SearchKey.Contains(input.str))
                .ToPagedList(input.page, input.size);
             
        }

        /// <summary>
        /// 新增知识库
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        public void AddWord(cts_Word info)
        {
            info.Gid= Guid.NewGuid().ToString();
            _wordRep.Insert(info);
        }
        /// <summary>
        /// 删除知识库
        /// </summary>     
        /// <returns></returns>
        
        public void DeleteWord(string id)
        {
            _wordRep.AsUpdateable().SetColumns(m=>m.sys_IsDelete==1).Where(m=>m.Gid==id).ExecuteCommand();
        }


        /// <summary>
        /// 查询项目报告
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public SqlSugarPagedXList<cts_ProjectReport> SearchProjectReport(SearchWordInput input)
        {
            return _reportRep.AsQueryable().WhereIF(input.wordsource > -1, m => m.WordSource == input.wordsource)
               .WhereIF(input.wordtype > -1, m => m.WordType == input.wordtype)
               .WhereIF(!string.IsNullOrEmpty(input.str), m => m.Name.Contains(input.str) || m.SearchKey.Contains(input.str))
               .ToPagedList(input.page, input.size);
        }

        /// <summary>
        /// 新增项目报告
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        public void AddProjectReport(cts_ProjectReport info)
        {
            info.Gid = Guid.NewGuid().ToString();
            _reportRep.Insert(info);
        }
        /// <summary>
        /// 删除知识库
        /// </summary>     
        /// <returns></returns>
        
        public void DeleteProjectReport(string id)
        {
            _reportRep.AsUpdateable().SetColumns(m => m.sys_IsDelete == 1).Where(m => m.Gid == id).ExecuteCommand();
        }
        /// <summary>
        /// 查询意见反馈
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public SqlSugarPagedXList<cts_Opinion> SearchOpinion(SearchTypeInputDto input)
        {
            return _optionRep.AsQueryable() 
              .WhereIF(input.type > -1, m => m.Type == input.type)
              .WhereIF(!string.IsNullOrEmpty(input.str), m => m.Desc.Contains(input.str) )
              .ToPagedList(input.page, input.size);
        }

        /// <summary>
        /// 新增意见反馈
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        public void AddOpinion(cts_Opinion info)
        {
            info.Gid = Guid.NewGuid().ToString();
            _optionRep.Insert(info);
        }
        /// <summary>
        /// 删除意见反馈
        /// </summary>     
        /// <returns></returns>
        
        public void DeleteOpinion(string id)
        {
            _optionRep.AsUpdateable().SetColumns(m => m.sys_IsDelete == 1).Where(m => m.Gid == id).ExecuteCommand();
        }

        /// <summary>
        /// 获取考勤规则
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public List<cts_CheckOnWorkRule> GetCheckOnWorkRule()
        {

            return _checkOnWorkRuleRep.GetList() ;
        }

        /// <summary>
        /// 更改考勤规则
        /// </summary>
        /// <returns></returns>
        [UnitOfWork]
        public void ChengeheckOnWorkRule(string id)
        {
            _checkOnWorkRuleRep.AsUpdateable().SetColumns(m => m.IsDefault == 0).Where(m => m.Gid != id).ExecuteCommand();
            _checkOnWorkRuleRep.AsUpdateable().SetColumns(m => m.IsDefault == 1).Where(m => m.Gid == id).ExecuteCommand();

        }

        /// <summary>
        /// 查看我当天的打卡记录
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public List<cts_CheckOnWork> GetMyTodayCheckOnWork(string date = "", string empid = "")
        {

            if (string.IsNullOrEmpty(empid))
            {
                empid = UserHelper.GetUserId();
            }
            return _checkOnWorkRep.AsQueryable().Where(m => m.sys_Creater == empid)
                .WhereIF(string.IsNullOrEmpty(date), m => m.CheckDate == DateTime.Now.Date)
                 .WhereIF(string.IsNullOrEmpty(date), m => m.CheckDate == date.ObjToDate()).ToList();

             
        }
        /// <summary>
        /// 统计我的考勤
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public dynamic SearchMyCheckOnWork(SearchDateInputDto input)
        {
            if (string.IsNullOrEmpty(input.empid))
            {
               input.empid = UserHelper.GetUserId();
            }

            var sqlSearch = $@"select sys_Creater,sys_CreaterName,CheckDate,datename(weekday, CheckDate) as CheckWeek,
                                    MIN( CASE WHEN CheckType=0 THEN CheckRecord END) CheckRecord1,
                                    MIN( CASE WHEN CheckType=3 THEN CheckRecord END) CheckRecord2,
                                    ISNULL(MIN( CASE WHEN CheckType=0 THEN CheckState END),9) CheckState1,
                                    ISNULL(MIN( CASE WHEN CheckType=3 THEN CheckState END),9) CheckState2
                                    from cts_CheckOnWork 
                                    where CheckDate>='{input.sdate}' and CheckDate<='{input.edate}' and sys_Creater='{input.empid}'
                                    group by sys_Creater,sys_CreaterName,CheckDate";

            return _checkOnWorkRep.AsSugarClient().Ado.SqlQuery<dynamic>(sqlSearch).ToList();

        }
        /// <summary>
        /// 统计考勤
        /// </summary>
        /// <returns></returns> 
        public dynamic SearchCheckOnWork(SearchDateInputDto input)
        {
            if (UserHelper.GetAuth() != (UserHelper.GetAuth() | 2))
            {
                input.empid = UserHelper.GetUserId(); 
            }
            var sqlSearch = $@"SELECT  ISNULL(A.Gid,C.sys_Creater) AS Gid,ISNULL(A.EmployeeName,C.sys_CreaterName) AS EmployeeName,ISNULL(A.WorkDate,C.CheckDate) AS WorkDate,ISNULL(A.DeWeek,C.CheckWeek) AS DeWeek,A.IsWork,A.Remark,C.sys_Creater,C.sys_CreaterName,C.CheckDate,C.CheckWeek,C.CheckRecord1,C.CheckRecord2,
		CheckRecordImg1,CheckRecordImg2,CheckRemark1,CheckRemark2,CheckAddress1,CheckAddress2,ISNULL(C.CheckState1,9) AS CheckState1,ISNULL(C.CheckState2,9) AS CheckState2
FROM(SELECT Gid,EmployeeName ,WorkDate,DeWeek ,B.IsWork,B.Remark
            FROM cts_Employee A 
            LEFT JOIN cts_WorkDay B ON   B.WorkDate>='{input.sdate}' and WorkDate<='{input.edate}' AND B.IsWork=1
            WHERE  A.Gid='{input.empid}'
     )A 
     FULL OUTER JOIN(SELECT sys_Creater,sys_CreaterName,CheckDate,datename(weekday, CheckDate) as CheckWeek,
        MIN( CASE WHEN CheckType=0 THEN CheckRecord END) CheckRecord1,
        MIN( CASE WHEN CheckType=3 THEN CheckRecord END) CheckRecord2,
        MIN( CASE WHEN CheckType=0 THEN CheckRecordImg END) CheckRecordImg1,
        MIN( CASE WHEN CheckType=3 THEN CheckRecordImg END) CheckRecordImg2,
        MIN( CASE WHEN CheckType=0 THEN CheckRemark END) CheckRemark1,
        MIN( CASE WHEN CheckType=3 THEN CheckRemark END) CheckRemark2,
        MIN( CASE WHEN CheckType=0 THEN CheckAddress END) CheckAddress1,
        MIN( CASE WHEN CheckType=3 THEN CheckAddress END) CheckAddress2,
        ISNULL(MIN( CASE WHEN CheckType=0 THEN CheckState END),9) CheckState1,
        ISNULL(MIN( CASE WHEN CheckType=3 THEN CheckState END),9) CheckState2
        FROM cts_CheckOnWork 
        WHERE CheckDate>='{input.sdate}' and CheckDate<='{input.edate}'   and sys_Creater='{input.empid}'
        GROUP BY sys_Creater,sys_CreaterName,CheckDate)C ON A.Gid=C.sys_Creater AND A.WorkDate=C.CheckDate 
        ORDER BY WorkDate
";
            return _checkOnWorkRep.AsSugarClient().Ado.SqlQuery<dynamic>(sqlSearch).ToList();

        }
        /// <summary>
        /// 统计考勤
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public dynamic SearchCheckOnWorkSta(SearchDateInputDto input)
        {
             
            var sqlSearch = $@" SELECT Gid,EmployeeName,
    SUM(CASE WHEN IsWork=1 THEN 1 ELSE 0 END) AS ShoudRecordCount,
    SUM(CASE WHEN CheckDate IS NOT NULL THEN 1 ELSE 0 END ) AS RecordCount,
    SUM(CASE WHEN CheckState1=1  THEN 1  ELSE 0 END ) AS CheckState1, 
    SUM(CASE WHEN CheckState2=2 THEN 1  ELSE 0 END ) AS CheckState2,
    SUM(CASE WHEN CheckState1=9 AND CheckState2=9  THEN 2  WHEN CheckState1=9 OR CheckState2=9 THEN 1 ELSE 0 END ) AS CheckState9
FROM(SELECT Gid,EmployeeName ,WorkDate,DeWeek ,B.IsWork,B.Remark
            FROM cts_Employee A 
            LEFT JOIN cts_WorkDay B ON   B.WorkDate>='{input.sdate}' and WorkDate<='{input.edate}'
            WHERE  A.IsDelete=0 AND A.Type=0 AND (A.Auth =1 OR A.Auth=11)
     )A 
     LEFT JOIN(SELECT sys_Creater,sys_CreaterName,CheckDate,datename(weekday, CheckDate) as CheckWeek,
		MIN( CASE WHEN CheckType=0 THEN CheckRecord END) CheckRecord1,
		MIN( CASE WHEN CheckType=3 THEN CheckRecord END) CheckRecord2,
		ISNULL(MIN( CASE WHEN CheckType=0 THEN CheckState END),9) CheckState1,
		ISNULL(MIN( CASE WHEN CheckType=3 THEN CheckState END),9) CheckState2
		FROM cts_CheckOnWork 
		WHERE CheckDate>='{input.sdate}' and CheckDate<='{input.edate}'   
		GROUP BY sys_Creater,sys_CreaterName,CheckDate)C ON A.Gid=C.sys_Creater AND A.WorkDate=C.CheckDate 
 GROUP BY Gid,EmployeeName";
            return _checkOnWorkRep.AsSugarClient().Ado.SqlQuery<dynamic>(sqlSearch).ToList();
        }

        /// <summary>
        /// 考勤打卡
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public void CheckOnWork(cts_CheckOnWork cw)
        { 

            cts_CheckOnWorkRule cru = _checkOnWorkRuleRep.GetFirst(m=>m.IsDefault==1);


            var nowTime = DateTime.Now;
            var cTime1 = DateTime.ParseExact(cru.CheckRecord1, "HH:mm:ss", CultureInfo.CurrentCulture);
            var cTime1Right = DateTime.ParseExact(cru.CheckRecord1Right, "HH:mm:ss", CultureInfo.CurrentCulture);
            var cTime4 = DateTime.ParseExact(cru.CheckRecord4, "HH:mm:ss", CultureInfo.CurrentCulture);

            cw.Gid = Guid.NewGuid().ToString();
            cw.sys_CreateDate = DateTime.Now;
            cw.sys_Creater = UserHelper.GetUserId();
            cw.sys_IsDelete = 0;
            cw.sys_CreaterName = UserHelper.GetUserName();
            cw.CheckRecord = nowTime;
            cw.CheckDate = nowTime;
            cw.RuleId = cru.Gid;
            if (cw.CheckType == 0)//上午上班
            {
                if (nowTime > cTime1Right)
                {
                   throw Oops.Bah("超出打卡时间范围");
                }
                if (nowTime > cTime1)
                {
                    cw.CheckState = 1;
                }
            }

            else if (cw.CheckType == 3)//下午下班
            {

                if (nowTime < cTime4)
                {
                    cw.CheckState = 2;
                }
            }
            _checkOnWorkRep.Insert(cw);
        }


        /// <summary>
        /// 查询图片库
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public SqlSugarPagedXList<cts_PhotoGroup> SearchPhotoGroup(SearchTypeInputDto input)
        {

            return _photoGroupRep.AsQueryable()
                .WhereIF(!string.IsNullOrEmpty(input.str), m => m.Name.Contains(input.str))
                .ToPagedList(input.page, input.size);
        }

        /// <summary>
        /// 新增图片库
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        public void AddPhotoGroup(cts_PhotoGroup info)
        {
            info.Gid = Guid.NewGuid().ToString();
            _photoGroupRep.Insert(info);
        }
        /// <summary>
        /// 删除图片库
        /// </summary>     
        /// <returns></returns>
        
        public void DeletePhotoGroup(string id)
        {
            _photoGroupRep.AsUpdateable().SetColumns(m => m.sys_IsDelete == 1).Where(m => m.Gid == id).ExecuteCommand();
        }

        /// <summary>
        /// 查询图片库
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public SqlSugarPagedXList<cts_Photo> SearchPhoto(SearchTypeInputDto input)
        {
            return _photoRep.AsQueryable()
              .Where(  m => m.GroupId==input.gid)
               .WhereIF(!string.IsNullOrEmpty(input.str), m => m.Remark.Contains(input.str))
              .ToPagedList(input.page, input.size);
        }

        /// <summary>
        /// 新增图片详情
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        public void AddPhoto(cts_Photo info)
        {
            info.Gid = Guid.NewGuid().ToString();
            _photoRep.Insert(info);
        }
        /// <summary>
        /// 删除图片详情
        /// </summary>     
        /// <returns></returns>
        
        public void DeletePhoto(string id)
        {
            _photoRep.AsUpdateable().SetColumns(m => m.sys_IsDelete == 1).Where(m => m.Gid == id).ExecuteCommand();
        }

        [AllowAnonymous]
        [HttpGet]
        public DateTime GetTime()
        {
            return DateTime.Now;
        }
    }
}
